<?php 
/**
 *会员管理
*/

namespace xhadmin\service\admin\record;

use xhadmin\CommonService;
use xhadmin\db\Customer;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\facade\Db;

class CustomerService extends CommonService {


	/*
 	* @Description  会员管理列表数据
 	* @param (输入参数：)  {array}        where 查询条件
 	* @param (输入参数：)  {int}          limit 分页参数
 	* @param (输入参数：)  {String}       field 查询字段
 	* @param (输入参数：)  {String}       orderby 排序字段
 	* @return (返回参数：) {array}        分页数据集
 	*/
	public static function pageList($where=[],$limit,$field='*',$orderby=''){
		try{
			$list = Customer::loadList($where,$limit,$field,$orderby);
			$count = Customer::countList($where);
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
		return ['list'=>$list,'count'=>$count];
	}


	public static function pageListA($where=[],$limit,$field='*',$orderby='',$status=0){
		try{
			$list = Customer::loadList($where,$limit,$field,$orderby);
			if(!empty($list)){
				$id_arr=array_column($list,'id');
				// $customer_list=Db::name('customer')->where('id','in',$id_arr)->column('birth_day','id');
				$customer_log_list=Db::name('customer_log')->where('c_id','in',$id_arr)->where('status','=',$status)->column('create_time','c_id');
				foreach ($list as $key => $value) {
					// $list[$key]['birth_day']=isset($customer_list[$value['id']]['birth_day']) ? $customer_list[$value['id']]['birth_day'] : '';
					$list[$key]['deliver_time']=isset($customer_log_list[$value['id']]) ? date('Y-m-d',$customer_log_list[$value['id']]) : '';
				}
			}
			$count = Customer::countList($where);
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
		return ['list'=>$list,'count'=>$count];
	}	


	/*
 	* @Description  添加
 	* @param (输入参数：)  {array}        data 原始数据
 	* @return (返回参数：) {bool}        
 	*/
	public static function add($data){
		try{
		    if(!isset($data['create_by'])) {
                $data['create_by'] = session('admin.userid');
            }
			$data['create_time'] = $data['update_time'] =time();
			$res = Customer::createData($data);
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
		return $res;
	}


	/*
 	* @Description  修改
 	* @param (输入参数：)  {array}        data 原始数据
 	* @return (返回参数：) {bool}        
 	*/
	public static function update($data){
		try{
			$data['update_time'] = time();
            //p($data);exit;
			//数据验证
			/*$rule = [
				'mobile'=>['unique:member','regex'=>'/^1[345678]\d{9}$/'],
				'email'=>['regex'=>'/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/'],
			];
			$msg = [
				'mobile.unique'=>'手机号已经存在',
				'mobile.regex'=>'手机号格式错误',
				'email.regex'=>'邮箱格式错误',
			];*/
//            $rule = [
//                'id_card'=>['unique','regex'=>'/^\d{13}$/'],
//            ];
//            $msg = [
//                'id_card.unique'=>'客户已经存在',
//            ];
            //self::validate($rule,$data,$msg);
            //p($data);exit;
			$res = Customer::edit($data);
		}catch(\Exception $e){
            throw new \Exception($e->getMessage());
		}
		return $res;
	}

	public static function editWhere($where = [],$data) {
        try{
            $data['update_time'] = time();
            $res = Customer::editWhere($where,$data);
        }catch(\Exception $e){
            throw new \Exception($e->getMessage());
        }
        return $res;
    }


	/*
 	* @Description  删除
 	* @param (输入参数：)  {array}        where 删除条件
 	* @return (返回参数：) {bool}        
 	*/
	public static function delete($where){
		try{
			$res = Customer::delete($where);
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
		return $res;
	}


	/*
 	* @Description  导出
 	* @param (输入参数：)  {array}        where 查询条件
 	* @return (返回参数：) {bool}        
 	*/
	public static function dumpData($where,$orderby,$field){
		try{
			$list = Customer::loadList($where,$limit=50000,'*',$orderby);
			if(!$list) throw new \Exception('没有数据');

			$map['menu_id'] = 526;
			$map['field'] = $field;
			$fieldList = db("field")->where($map)->order('id asc')->select()->toArray();

			$spreadsheet = new Spreadsheet();
			$sheet = $spreadsheet->getActiveSheet();
			//excel表头
			foreach($fieldList as $key=>$val){
				$sheet->setCellValue(\xhadmin\CommonService::getTag($key+1).'1',$val['name']);
			}
			//excel表主体内容
			foreach($list as $k=>$v){
				foreach($fieldList as $m=>$n){
					if(in_array($n['type'],[7,12])){
						$v[$n['field']] = date('Y-m-d H:i:s',$v[$n['field']]);
					}
					if(in_array($n['type'],[2,3,23,27]) && !empty($n['config'])){
						$v[$n['field']] = getFieldVal($v[$n['field']],$n['config']);
					}
					if($n['type'] == 17){
						foreach(explode('|',$n['field']) as $q){
							$v[$n['field']] .= $v[$q].'-';
						}
						$v[$n['field']] = rtrim($v[$n['field']],'-');
					}
					$sheet->setCellValueExplicit(\xhadmin\CommonService::getTag($m+1).($k+2),$v[$n['field']],\PhpOffice\PhpSpreadsheet\Cell\DataType::TYPE_STRING);
					$v[$n['field']] = '';
				}
			}
			
			$filename = date('YmdHis');
			header('Content-Type: application/vnd.ms-excel');
			header('Content-Disposition: attachment;filename='.$filename.'.'.config('my.import_type')); 
			header('Cache-Control: max-age=0');
			$writer = new Xlsx($spreadsheet); 
			$writer->save('php://output');
		}catch(\Exception $e){
			throw new \Exception($e->getMessage());
		}
	}


}

